/**
 * UI 工具类
 * 负责处理用户界面相关的操作
 */
class UIUtils {
    static showLoading(message = '正在处理中...') {
        const loadingOverlay = document.getElementById('loading');
        if (loadingOverlay) {
            const spinner = loadingOverlay.querySelector('p');
            if (spinner) {
                spinner.textContent = message;
            }
            loadingOverlay.classList.add('show');
        }
    }

    static hideLoading() {
        const loadingOverlay = document.getElementById('loading');
        if (loadingOverlay) {
            loadingOverlay.classList.remove('show');
        }
    }

    static showMessage(message, type = 'info', duration = 3000) {
        const messageEl = document.createElement('div');
        messageEl.className = `status-message ${type}`;
        messageEl.textContent = message;

        const container = document.querySelector('.status-message-container') || this.createMessageContainer();
        container.appendChild(messageEl);

        setTimeout(() => {
            if (messageEl.parentNode) {
                messageEl.parentNode.removeChild(messageEl);
            }
        }, duration);
    }

    static createMessageContainer() {
        const container = document.createElement('div');
        container.className = 'status-message-container';
        container.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 10000;
            display: flex;
            flex-direction: column;
            gap: 10px;
        `;
        document.body.appendChild(container);
        return container;
    }

    static async switchTab(tabId) {
        // 更新导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });

        const targetNavItem = document.querySelector(`[data-tab="${tabId}"]`);
        if (targetNavItem) {
            targetNavItem.classList.add('active');
        }

        // 使用PageLoader加载页面
        if (window.pageLoader) {
            await window.pageLoader.showPage(tabId);
        } else {
            // 备用方案：直接调用pageLoad
            this.pageLoad(tabId);
        }
    }

    static pageLoad(tabId) {
        switch (tabId) {
            case 'home':
                this.loadHomePage();
                break;
            case 'setup':
                this.loadSetupPage();
                break;
            case 'tasks':
                this.loadTasksPage();
                break;
            case 'history':
                this.loadHistoryPage();
                break;
        }
    }

    static async loadHomePage() {
        try {
            // 等待 DOM 元素加载
            
            // 添加检测开始日志
            this.addDetectionLog('开始检测 Claude Code 安装状态...', 'info');
            
            // 检查 Claude Code 状态
            this.addDetectionLog('检查 Claude Code 基本状态...', 'info');
            const claudeResult = await apiService.checkClaudeCode();
            const claudeStatus = document.getElementById('claude-status');
            if (claudeStatus) {
                claudeStatus.textContent = claudeResult.installed ? '已安装' : '未安装';
                this.addDetectionLog(`Claude Code 状态: ${claudeResult.installed ? '已安装' : '未安装'}`, 
                    claudeResult.installed ? 'success' : 'warning');
            }

            // 获取详细的 Claude Code 信息
            this.addDetectionLog('获取详细的 Claude Code 信息...', 'info');
            const claudeInfoResult = await apiService.getClaudeCodeInfo();
            if (claudeInfoResult.success && claudeInfoResult.info) {
                const info = claudeInfoResult.info;
                
                // 显示工作目录
                if (info.workingDirectory) {
                    const workingDirItem = document.getElementById('working-directory-item');
                    const workingDirValue = document.getElementById('working-directory');
                    if (workingDirItem && workingDirValue) {
                        workingDirItem.style.display = 'block';
                        workingDirValue.textContent = info.workingDirectory;
                        this.addDetectionLog(`工作目录: ${info.workingDirectory}`, 'success');
                    }
                }

                // 获取版本信息
                this.addDetectionLog('获取 Claude Code 版本信息...', 'info');
                const versionResult = await apiService.getClaudeCodeVersion();
                if (versionResult.success && versionResult.version && versionResult.version.success) {
                    const versionItem = document.getElementById('version-item');
                    const versionValue = document.getElementById('version-info');
                    if (versionItem && versionValue) {
                        versionItem.style.display = 'block';
                        const version = versionResult.version.version || '未知版本';
                        versionValue.textContent = version;
                        this.addDetectionLog(`版本信息: ${version}`, 'success');
                    }
                } else {
                    this.addDetectionLog('无法获取版本信息', 'warning');
                }
            } else {
                this.addDetectionLog('获取 Claude Code 详细信息失败', 'error');
            }

            // 检查 API Key 状态
            this.addDetectionLog('检查 API Key 状态...', 'info');
            const keyResult = await apiService.loadApiKey();
            const apiKeyStatus = document.getElementById('api-key-status');
            if (apiKeyStatus) {
                apiKeyStatus.textContent = keyResult.apiKey ? '已配置' : '未配置';
                this.addDetectionLog(`API Key 状态: ${keyResult.apiKey ? '已配置' : '未配置'}`, 
                    keyResult.apiKey ? 'success' : 'warning');
            }

            this.addDetectionLog('检测完成', 'success');
        } catch (error) {
            console.error('加载首页数据失败:', error);
            this.addDetectionLog(`检测过程中发生错误: ${error.message}`, 'error');
        }
    }


    static async loadSetupPage() {
        // 设置页面的初始化逻辑
    }

    static async loadTasksPage() {
        // 任务页面的初始化逻辑
    }

    static async loadHistoryPage() {
        try {
            const historyContainer = document.querySelector('.history-container');
            
            if (!historyContainer) return;

            const result = await apiService.getTaskHistory();
            if (result.success && result.history.length > 0) {
                this.renderHistory(result.history, historyContainer);
            } else {
                historyContainer.innerHTML = `
                    <div class="history-placeholder">
                        <i class="fas fa-history"></i>
                        <h3>暂无历史记录</h3>
                        <p>开始执行任务后，执行记录将在这里显示</p>
                    </div>
                `;
            }
        } catch (error) {
            console.error('加载历史记录失败:', error);
        }
    }

    static renderHistory(history, container) {
        const historyHTML = history.map(item => `
            <div class="history-item">
                <div class="history-header">
                    <span class="history-time">${new Date(item.timestamp).toLocaleString()}</span>
                    <span class="history-status ${item.success ? 'success' : 'error'}">
                        ${item.success ? '成功' : '失败'}
                    </span>
                </div>
                <div class="history-task">${item.task}</div>
                ${item.result ? `<div class="history-result">${item.result.substring(0, 200)}...</div>` : ''}
                ${item.error ? `<div class="history-error">错误: ${item.error}</div>` : ''}
            </div>
        `).join('');

        container.innerHTML = historyHTML;
    }

    static async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            this.showMessage('已复制到剪贴板', 'success');
        } catch (error) {
            console.error('复制失败:', error);
            this.showMessage('复制失败', 'error');
        }
    }

    static addDetectionLog(message, type = 'info') {
        const logContainer = document.getElementById('detection-log');
        if (!logContainer) {
            console.log(`[DetectionLog] ${message}`);
            return;
        }

        try {
            const logItem = document.createElement('div');
            logItem.className = `log-item ${type}`;
            
            const time = new Date().toLocaleTimeString();
            logItem.innerHTML = `
                <span class="log-time">[${time}]</span>
                <span class="log-message">${message}</span>
            `;

            logContainer.appendChild(logItem);
            
            // 自动滚动到底部
            logContainer.scrollTop = logContainer.scrollHeight;
        } catch (error) {
            console.error('添加检测日志失败:', error);
            console.log(`[DetectionLog] ${message}`);
        }
    }

    static clearDetectionLog() {
        const logContainer = document.getElementById('detection-log');
        if (logContainer) {
            logContainer.innerHTML = `
                <div class="log-item">
                    <span class="log-time">[系统]</span>
                    <span class="log-message">日志已清空</span>
                </div>
            `;
        }
    }

    static async waitForElement(elementId, timeout = 5000) {
        return new Promise((resolve, reject) => {
            const element = document.getElementById(elementId);
            if (element) {
                resolve(element);
                return;
            }

            const startTime = Date.now();
            const checkInterval = setInterval(() => {
                const element = document.getElementById(elementId);
                if (element) {
                    clearInterval(checkInterval);
                    resolve(element);
                } else if (Date.now() - startTime > timeout) {
                    clearInterval(checkInterval);
                    reject(new Error(`Element ${elementId} not found within ${timeout}ms`));
                }
            }, 100);
        });
    }

}

// 导出到全局
window.UIUtils = UIUtils;
